package nocannobb.ucanuup.daringshai.activity;

import java.io.IOException;
import java.util.List;

import nocannobb.ucanuup.daringshai.R;
import nocannobb.ucanuup.daringshai.adapter.StaggeredAdapter;
import nocannobb.ucanuup.daringshai.bitmaputil.Helper;
import nocannobb.ucanuup.daringshai.bitmaputil.ImageFetcher;
import nocannobb.ucanuup.daringshai.debugutil.BeautyLog;
import nocannobb.ucanuup.daringshai.model.Beauty;
import nocannobb.ucanuup.daringshai.model.BeautyList;
import nocannobb.ucanuup.daringshai.releaseconst.ReleaseConst;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.origamilabs.library.views.StaggeredGridView;
import com.origamilabs.library.views.StaggeredGridView.OnItemClickListener;
import com.origamilabs.library.views.StaggeredGridView.OnScrollListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    private ImageFetcher mImageFetcher;

    private StaggeredGridView beautyscroll;
    private StaggeredAdapter mAdapter;

    private ContentTask task = new ContentTask(this, 2);

    private int pageNum = 1;
    private boolean refreshing = false;
    private Activity me;

	private ImageView shareiv;
    
    /**
     * •确保在所有的Activity中都调用 MobclickAgent.onResume()
     * 和MobclickAgent.onPause()方法，这两个调用将不会阻塞应用程序的主线程，也不会影响应用程序的性能。
     * •注意如果您的Activity之间有继承或者控制关系请不要同时在父和子Activity中重复添加onPause和onResume方法
     * ，否则会造成重复统计(eg.使用TabHost、TabActivity、ActivityGroup时)。
     * •当用户两次使用之间间隔超过30秒时，将被认为是两个的独立的session
     * (启动)，例如用户回到home，或进入其他程序，经过一段时间后再返回之前的应用
     * 。可通过接口：MobclickAgent.setSessionContinueMillis(long interval) 来设置这个间隔。
     */
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    /*
     * 添加umengsdk session统计，每个展示activity
     * 
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        me = this;
        setContentView(R.layout.activity_main);
        BeautyLog.v(TAG, "Beauty start");
        // 更新服务器配置的统计消息发送策略。无配置默认定时发送
        MobclickAgent.updateOnlineConfig(this);
        // 打开调试模式后，您可以在logcat中查看您的数据是否成功发送到友盟服务器，以及集成过程中的出错原因等
        MobclickAgent.setDebugMode(true);

        mImageFetcher = new ImageFetcher(this, 240);
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);

        beautyscroll = (StaggeredGridView) findViewById(R.id.beautyscroll);
        int margin = getResources().getDimensionPixelSize(R.dimen.margin);
        beautyscroll.setItemMargin(margin, margin, margin, margin); // set the
        beautyscroll.setFastScrollEnabled(false); // GridView
                                                  // margin
        beautyscroll.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(StaggeredGridView view,
                    int scrollState) {

            }

            @Override
            public void onScroll(StaggeredGridView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {
                if (!refreshing) {
                    if (firstVisibleItem + visibleItemCount >= totalItemCount
                            && visibleItemCount != 0) {
                        AddItemToContainer(++pageNum, 1);
                        refreshing = true;
                    }
                }
            }
        });

        beautyscroll.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(StaggeredGridView parent, View view,
                    int position, long id) {
                MobclickAgent.onEvent(MainActivity.this,
                        ReleaseConst.EVENT_CLICK_BEAUTY_LIST_ITEM);
                Beauty mBeauty = (Beauty) mAdapter.getItem(position);
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, BeautyWeb.class);
                intent.putExtra("url", mBeauty.getUid());
                startActivity(intent);
            }
        });

        mAdapter = new StaggeredAdapter(this, mImageFetcher);
        beautyscroll.setAdapter(mAdapter);

        AddItemToContainer(pageNum, 1);

        final UMSocialService mController = UMServiceFactory
                .getUMSocialService("com.umeng.share", RequestType.SOCIAL);
        // 设置分享内容
        mController
                .setShareContent("友盟社会化组件（SDK）让移动应用快速整合社交分享功能，http://www.umeng.com/social");
        // 设置分享图片, 参数2为图片的url地址
        mController.setShareMedia(new UMImage(this,
                "http://www.umeng.com/images/pic/banner_module_social.png"));
        shareiv = (ImageView) findViewById(R.id.share_btn);
        shareiv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 是否只有已登录用户才能打开分享选择页
                mController.openShare(me, false);
            }
        });

    }

    private void AddItemToContainer(int pageindex, int type) {
        if (task.getStatus() != Status.RUNNING) {
            String url = ReleaseConst.SERVER_BEAUTY_LIST_URL + pageindex;
            ContentTask task = new ContentTask(this, type);
            task.execute(url);
        }
    }

    private class ContentTask extends AsyncTask<String, Integer, List<Beauty>> {

        private Context mContext;
        private int mType = 1;

        public ContentTask(Context context, int type) {
            super();
            mContext = context;
            mType = type;
        }

        @Override
        protected List<Beauty> doInBackground(String... params) {
            try {
                return parseNewsJSON(params[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<Beauty> result) {
            if (mType == 1) {

                mAdapter.addItemLast(result);
                mAdapter.notifyDataSetChanged();
                refreshing = false;

            } else if (mType == 2) {
                mAdapter.addItemLast(result);
                mAdapter.notifyDataSetChanged();

            }

        }

        @Override
        protected void onPreExecute() {
        }

        public List<Beauty> parseNewsJSON(String url) throws IOException {
            BeautyList beautyList = null;
            String json = "";
            if (Helper.checkConnection(mContext)) {
                try {
                    json = Helper.getStringFromUrl(url);

                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            if (null != json) {
                Gson gson = new Gson();
                beautyList = gson.fromJson(json, BeautyList.class);
            }
            if (beautyList == null)
                return null;
            return beautyList.getPosts();
        }
    }

}
